package com.topnav.mc.config.proxy;

import com.js.lib.cache.Cache;
import com.js.lib.utils.JsonUtil;
import com.topnav.mc.admin.entity.GbServer;
import com.topnav.mc.admin.service.IGbServerService;
import com.topnav.mc.common.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.mitre.dsmiley.httpproxy.ProxyServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.ConnectException;


/**
 * 代理API
 */
@Configuration
@Slf4j
public class ProxyServletConfig {
    @Value("${server.port}")
    private int serverPort;
    @Resource(name="sysCache")
    private Cache sysCache;

    @Bean
    public ServletRegistrationBean gbServerServletRegistrationBean(){
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new GbServerProxyServlet(),"/gbapi/*");
        servletRegistrationBean.setName("gbserver_proxy");
        servletRegistrationBean.addInitParameter("targetUri", "http://127.0.0.1:6080");
        servletRegistrationBean.addUrlMappings();
        if (log.isDebugEnabled()) {
            servletRegistrationBean.addInitParameter("log", "true");
        }
        return servletRegistrationBean;
    }

    /** 国标服务器代理 */
    class GbServerProxyServlet extends ProxyServlet {
        @Override
        protected String rewriteQueryStringFromRequest(HttpServletRequest servletRequest, String queryString) {
            String queryStr = super.rewriteQueryStringFromRequest(servletRequest, queryString);
            return queryStr;
        }

        /**
         * 异常处理
         */
        @Override
        protected void handleRequestException(HttpRequest proxyRequest, HttpResponse proxyResonse, Exception e){
            try {
                super.handleRequestException(proxyRequest, proxyResonse, e);
            } catch (ServletException servletException) {
                log.error("国标 代理失败： ", e);
            } catch (IOException ioException) {
                if (ioException instanceof ConnectException) {
                    log.error("国标 连接失败");
                } else if (ioException instanceof ClientAbortException) {
                    log.error("国标: 用户已中断连接，代理终止");
                } else {
                    log.error("国标 代理失败： ", e);
                }
            } catch (RuntimeException exception){
                log.error("国标 代理失败： ", e);
            }
        }

        /**
         * 对于未按照格式请求的可以直接返回404
         */
        @Override
        protected String getTargetUri(HttpServletRequest servletRequest) {
            String requestURI = servletRequest.getRequestURI();
            log.info(requestURI);

            GbServer gbServer = getGbServer(requestURI);

            String uri = null;
            if (gbServer != null) {
//                String realRequestURI = requestURI.substring(requestURI.indexOf(mediaInfo.getId())+ mediaInfo.getId().length());
                uri = String.format("http://%s:%s", gbServer.getHost(), gbServer.getApiPort());
            }else {
                uri = "http://127.0.0.1:" + serverPort +"/index/hook/null"; // 只是一个能返回404的请求而已， 其他的也可以
            }
            return uri;
        }

        /**
         * 动态替换请求目标
         */
        @Override
        protected HttpHost getTargetHost(HttpServletRequest servletRequest) {
            String requestURI = servletRequest.getRequestURI();
            log.info(requestURI);
            GbServer gbServer = getGbServer(requestURI);
            HttpHost host;
            if (gbServer != null) {
                host = new HttpHost(gbServer.getHost(), Integer.valueOf(gbServer.getApiPort()));
            }else {
                host = new HttpHost("127.0.0.1", serverPort);
            }
            return host;
        }
        /**
         * 去掉url中的标志信息
         */
        @Override
        protected String rewriteUrlFromRequest(HttpServletRequest servletRequest) {
            String requestURI = servletRequest.getRequestURI();
            log.info(requestURI);
            GbServer gbServer = getGbServer(requestURI);
            String url = super.rewriteUrlFromRequest(servletRequest);
            if (gbServer == null) {
                return  url;
            }
            url = url.replace(gbServer.getId() + "/","");
            return url;//url.replace(gbServer.getId() + "/", "");
        }

        /**
         * 允许夸域，不知这个能不能解决
         * @param servletRequest
         * @param servletResponse
         * @param proxyRequest
         * @return
         * @throws IOException
         */
        @Override
        protected HttpResponse doExecute(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
                                         HttpRequest proxyRequest) throws IOException {

            proxyRequest.removeHeaders("origin");
            HttpResponse response = super.doExecute(servletRequest, servletResponse, proxyRequest);
            response.setHeader("Access-Control-Allow-Origin", "*");
            //response.removeHeaders("Access-Control-Allow-Origin");
            //response.setHeader("Access-Control-Allow-Credentials","true");
            //response.removeHeaders("Access-Control-Allow-Credentials");

            return response;
        }

        /**
         * 根据uri获取GB服务器信息
         */
        private GbServer getGbServer(String uri){
            String[] split = uri.split("/");
            String id = split[2];
            Object obj = null;
            if ((obj = sysCache.hget(Constant.CACHE_KEY_GBSERVER, id))!=null){
                return (GbServer)obj;//JsonUtil.fromJson(obj.toString(),GbServer.class);
            }
            return null;
        }
    }

}
